using System.Linq;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.GamePlay;

namespace IQIGame.Onigao.Logic
{
    public partial class SkillTrigger_SelfAddBuff : SkillTrigger
    {
        protected override ESkillTriggerType triggerType => ESkillTriggerType.SelfAddBuff;

        public int buffID;
        public int tag;

        protected override void OnInitialize(Skill rSkill, TriggerConfig rConfig)
        {
            base.OnInitialize(rSkill, rConfig);
            if (rConfig.customConfig is SkillTrigger_SelfAddBuff_ConfigData rConfigData)
            {
                this.buffID = rConfigData.buffID;
                this.tag = rConfigData.tag;
            }
        }

        protected override void OnEnable()
        {
            base.OnEnable();
            this.AddListener<BuffHandler>(EBattleTriggerType.Battle_AddBuff, this.OnEvent);
        }

        private void OnEvent(BuffHandler rBuffHandler)
        {
            var rTarget = rBuffHandler.target;
            var nBuffID = rBuffHandler.buffID;
            if (rTarget.unit.GUID == this.executer.GUID)
            {
                if (this.buffID > 0 && this.buffID != nBuffID)
                {
                    return;
                }

                var rBuffConfig = TableCenter.buff.Get(this.buffID);
                if (rBuffConfig == null || (this.tag > 0 && !rBuffConfig.Tag.Contains(this.tag)))
                {
                    return;
                }
                var rVirInput = ClassPool.Get<SelectParam>();
                rVirInput.unit = this.skill.executer;
                rVirInput.pos = rVirInput.unit.pos;
                this.OnTrigger(rVirInput, rBuffHandler);
            }
        }

        public override void OnReset()
        {
            base.OnReset();
            this.buffID = 0;
            this.tag = 0;
        }

        public override void Free()
        {
            ClassPool.Put(this);
        }

#if UNITY_EDITOR
        public override string ToString()
        {
            return $"自身添加buff:{this.buffID}";
        }
#endif
    }
}